const express = require('express');
const os = require('os');
const net = require("net");
const cors = require('cors');

function getLocalIpAddress() {
  const interfaces = os.networkInterfaces();
  for (const name of Object.keys(interfaces)) {
    for (const iface of interfaces[name]) {
      // 跳过非内部的（即公共的）和非IPv4的地址
      if (!iface.internal && iface.family === 'IPv4') {
        return iface.address;
      }
    }
  }
}

function sendTcpMessage(message) {
  const client = new net.Socket();
  client.connect(4220, getLocalIpAddress(), () => {
    console.log('Connected to TCP Server');
    client.write(message);
  });

  client.on('data', (data) => {
    console.log('Received: ' + data);
    client.destroy(); // kill client after server's response
  });

  client.on('close', () => {
    console.log('Connection closed');
  });
}

const app = express()

app.use(cors())

app.get('/send', (req, res) => {
  const message = req.query.message;
  sendTcpMessage(message);
  res.send({ code: 200, msg: "响应get请求成功", status: 1 });
});

app.listen(3000).on('listening', () => {
  console.log(`server started at http://${getLocalIpAddress()}:3000`)
});
